package org.dromara.visitor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.visitor.domain.dto.*;
import org.dromara.visitor.domain.entity.PhoneBook;
import org.dromara.visitor.mapper.PhoneBookMapper;
import org.dromara.visitor.service.PhoneBookService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class PhoneBookServiceImpl extends ServiceImpl<PhoneBookMapper, PhoneBook> implements PhoneBookService {
    @Resource
    private PhoneBookMapper phoneBookMapper;
    @Override
    public void add(PhoneBookAddReq addReq) {
        //手机号姓名唯一
        LambdaQueryWrapper<PhoneBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PhoneBook::getApprovePhone, addReq.getApprovePhone());
        if(addReq.getId() != null){
            queryWrapper.ne(PhoneBook::getId,addReq.getId());
        }
        PhoneBook phoneBook = phoneBookMapper.selectOne(queryWrapper);
        if(phoneBook != null){
            throw new ServiceException("该手机号已存在");
        }
        LoginUser loginUser = LoginHelper.getLoginUser();
        PhoneBook phoneBook1 = new PhoneBook();
        BeanUtils.copyProperties(addReq,phoneBook1);
        if(phoneBook1.getId() == null){
            phoneBook1.setCreateBy(loginUser.getUserId());
            phoneBook1.setCreateTime(LocalDateTime.now());
        }
        phoneBook1.setUpdateBy(loginUser.getUserId());
        phoneBook1.setUpdateTime(LocalDateTime.now());
        this.saveOrUpdate(phoneBook1);
    }

    @Override
    public void setApproveLevel(Long id, Long approveId) {
        PhoneBook phoneBook = this.getById(id);
        if(approveId != null){
            PhoneBook approve = this.getById(approveId);
            phoneBook.setApproveLevel(2);
            phoneBook.setSecondName(approve.getApproveName());
            phoneBook.setSecondPhone(approve.getApprovePhone());
            phoneBook.setSecondBookId(approveId);
            this.updateById(phoneBook);
        }else{
            //设置一级审批
            UpdateWrapper<PhoneBook> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id",phoneBook.getId());
            updateWrapper.set("approve_level",1);
            updateWrapper.set("second_name",null);
            updateWrapper.set("second_phone",null);
            updateWrapper.set("second_book_id",null);
            this.update(updateWrapper);
        }


    }

    @Override
    public void setBatchApproveLevel(List<Long> ids, Long approveId) {
        List<PhoneBook> phoneBooks = phoneBookMapper.selectByIds(ids);
        PhoneBook approve = null;
        if(approveId != null){
            approve = this.getById(approveId);
            for(PhoneBook phoneBook : phoneBooks){
                phoneBook.setApproveLevel(2);
                phoneBook.setSecondName(approve.getApproveName());
                phoneBook.setSecondPhone(approve.getApprovePhone());
                phoneBook.setSecondBookId(approveId);
            }
            this.updateBatchById(phoneBooks);
            return;
        }
        UpdateWrapper<PhoneBook> updateWrapper = new UpdateWrapper<>();
        List<Long> idList = phoneBooks.stream().map(PhoneBook::getId).collect(Collectors.toList());
        updateWrapper.in("id",idList);
        updateWrapper.set("approve_level",1);
        updateWrapper.set("second_name",null);
        updateWrapper.set("second_phone",null);
        updateWrapper.set("second_book_id",null);
        this.update(updateWrapper);

    }

    @Override
    public Page<PhoneBookResp> listPage(PhoneBookQueryReq queryReq) {
        Page page = new Page(queryReq.getPageNum(),queryReq.getPageSize());
        List<PhoneBookResp> list = phoneBookMapper.listPage(page,queryReq);
        page.setRecords(list);
        return page;
    }

    @Override
    public void importExcel(List<PhoneBookImportExcel> list) {
        List<DeptBO> deptBOS = phoneBookMapper.listAllDepts();
        Map<String,DeptBO> map = deptBOS.stream().collect(Collectors.toMap(DeptBO::getDeptName,deptBO -> deptBO));
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<PhoneBook> books = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        int i = 0;
        for(PhoneBookImportExcel excel : list){
            i++;
            if(StringUtils.isBlank(excel.getCompanyName())){
                throw new ServiceException("第"+i+"行公司不能为空");
            }
            DeptBO deptBO = map.get(excel.getCompanyName());
            if(deptBO == null){
                throw new ServiceException("第"+i+"行公司不存在");
            }
            if(StringUtils.isBlank(excel.getFirstDepartmentName())){
                throw new ServiceException("第"+i+"行一级部门不能为空");
            }
            DeptBO deptBO1 = map.get(excel.getFirstDepartmentName());
            if(deptBO1 == null){
                throw new ServiceException("第"+i+"行一级部门不存在");
            }
            if(StringUtils.isBlank(excel.getSecondDepartmentName())){
                throw new ServiceException("第"+i+"行二级部门不能为空");
            }
            DeptBO deptBO2 = map.get(excel.getSecondDepartmentName());
            if(deptBO2 == null){
                throw new ServiceException("第"+i+"行二级部门不存在");
            }
            PhoneBook phoneBook = new PhoneBook();
            BeanUtils.copyProperties(excel,phoneBook);
            phoneBook.setCompanyId(deptBO.getDeptId());
            phoneBook.setFirstId(deptBO1.getDeptId());
            phoneBook.setSecondId(deptBO2.getDeptId());
            phoneBook.setCreateBy(loginUser.getUserId());
            phoneBook.setCreateTime(now);
            phoneBook.setUpdateBy(loginUser.getUserId());
            phoneBook.setUpdateTime(now);
            books.add(phoneBook);
        }
        this.saveBatch(books);
    }
}
